const Mock = require('mockjs')
const express = require('express')
const router =express.Router()
const SortBlogModel = require('../models/sortBlog')
const SortModel = require('../models/sort')
const mongoose = require('mongoose')
mongoose.connect('mongodb://localhost:27017/Blog')

router.get('/getSort',(req,res,next)=>{
  const {parent_sort_id} = req.query
  {SortModel.aggregate([
      {
        $match: parent_sort_id?{parent_sort_id:parseInt(parent_sort_id)}:{}
      },
      {
        $lookup: {
          from: 'sortblogs',
          localField: 'sort_id',
          foreignField: 'sort_id',
          as: 'sort_list',
        }
      }
    ]).then(result=>{
      res.json({
      code:200,
      data:result,
      message:'查询成功',
    })
  })}
})

router.get('/getBlog',(req,res,next)=>{
  const {sort_id} = req.query
  SortBlogModel.aggregate([
    {
      $match: sort_id?{sort_id:parseInt(sort_id)}:{}
    },
    {
      $lookup: {
        from: 'blogs',
        localField: 'blog_id',
        foreignField: 'blog_id',
        as: 'sort_list',
      }
    }
  ]).then(result=>{
      res.json({
      code:200,
      data:result,
      message:'查询成功',
    })
  })
})

router.post('/setSort',(req,res,next)=>{
  const {sort_id,blog_id} = req.body

  const sort = new SortBlogModel({
      sort_id,
      blog_id,
  })
  sort.save().then(result => {
      res.json({
          code:200,
          data:result,
          message:'创建完成',
      })
  })
})

router.delete('/delete',(req,res,next)=>{
  const {blog_id} = req.body

  SortBlogModel.deleteOne({blog_id}).then(result=>{
      res.json({
          code:200,
          data:{
              result
          },
          message:'删除完成',
      })
  })
})

router.post('/create',(req,res,next)=>{
  const {parent_sort_id,sort_name,sort_description} = req.body

  SortModel.find().then(result=>{
      const sort = new SortModel({
          sort_id:result.length,
          parent_sort_id,
          sort_name,
          sort_description
      })
      sort.save().then(result => {
          res.json({
              code:200,
              data:{
                  result
              },
              message:'创建完成',
          })
      })
  })
})

module.exports = router